﻿package com.alstudio.ui.module.user;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.content.Context;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.module.xmpp.request.ALUiXmppRequestCreator;
import com.alstudio.pojo.module.user.User;
import com.alstudio.ui.base.TitleBarActivity;
import com.alstudio.utils.android.color.ALColorUtils;
import com.alstudio.utils.formater.age.ALAgeFormatter;
import com.alstudio.utils.formater.age.ConstellationUtil;
import com.alstudio.utils.formater.time.ALTimeUtils;
import com.alstudio.utils.log.ALLog;
import com.alstudio.view.wheel.widget.OnWheelChangedListener;
import com.alstudio.view.wheel.widget.WheelView;
import com.alstudio.view.wheel.widget.adapters.ArrayWheelAdapter;
import com.alstudio.view.wheel.widget.adapters.NumericWheelAdapter;
import com.loovee.imaohu.R;

public class EditBirthDayActivity extends TitleBarActivity {

	private TextView et_age, et_constellation;
	private WheelView year, month, day;
	private String brithYears[];
	private String brithMonths[];
	private String brithDays[];
	private int indexY = 0;
	private int indexM = 0;
	private int indexD = 0;
	private static String save_brithyear = "";
	private static String save_brithmonth = "";
	private static String save_brithday = "";
	private String brithyear = "";
	private String brithmonth = "";
	private String brithday = "";
	private String thisYear = "";

	private String constellation = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setupView(this, getClass().getSimpleName());
	}

	/* (non-Javadoc)
	 * @see com.alstudio.ui.base.BaseActivity#setupView(android.content.Context, java.lang.String)
	 */
	@Override
	protected void setupView(Context context, String name) {
		// TODO Auto-generated method stub
		super.setupView(context, name);
		setTitleBarContentView(R.layout.edit_birthday);
		initData();
		initUI();
	}
	
	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		brithYears = ALTimeUtils.getDateYears();
		brithMonths = getResources().getStringArray(R.array.month);
		brithDays = getResources().getStringArray(R.array.day);

		indexY = brithYears.length - 1;
		indexM = brithMonths.length / 2;
		indexD = brithDays.length / 2;
	}

	private void initUI() {

		et_age = (TextView) findViewById(R.id.et_age);
		et_constellation = (TextView) findViewById(R.id.et_constellation);
		year = (WheelView) findViewById(R.id.brith_year);
		month = (WheelView) findViewById(R.id.brith_mouth);
		day = (WheelView) findViewById(R.id.brith_day);

		String birth = ALLocalEnv.getLocalEnv().getMyProfile().getBirtyday();
		String constellations = ALLocalEnv.getLocalEnv().getMyProfile().getConstellations();
		if (!TextUtils.isEmpty(birth) && birth.indexOf("-") != -1) {
			String yearItem = birth.substring(0, birth.indexOf("-"));

			Calendar now = Calendar.getInstance();
			yearItem = (now.get(Calendar.YEAR) - Integer.parseInt(yearItem))
					+ "";

			et_age.setText(yearItem);
		}
		if (!TextUtils.isEmpty(constellations)) {
			et_constellation.setText(constellations);
		}

		setBirthDay();
		setCenterTextViewMessage(R.string.TxtBirthDate);
	}

	/**
	 * 设置生日
	 */
	private void setBirthDay() {

		initData();

		String bry = "";
		String brm = "";
		String brd = "";
		String[] britydays = null;

		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
			Date now = new Date();
			String nowdate = df.format(now);

			britydays = nowdate.split("/");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		try {
			if (britydays.length == 3) {
				bry = britydays[0];
				brm = britydays[1];
				brd = britydays[2];
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		String birth = ALLocalEnv.getLocalEnv().getMyProfile().getBirtyday();
		String yearItem = "";
		String monthItem = "";
		String dayItem = "";
		if (!TextUtils.isEmpty(birth)) {
			String a[] = birth.split("-");

			yearItem = a[0];
			monthItem = a[1];
			dayItem = a[2];
		}

		if (!"".equals(yearItem) && !"".equals(monthItem)
				&& !"".equals(dayItem)) {

			indexY = getStringArrayIndex(brithYears, yearItem);
			indexM = getStringArrayIndex(brithMonths, monthItem);
			indexD = getStringArrayIndex(brithDays, dayItem);
		} else {
		}

		year.setViewAdapter(new DateArrayAdapter(this, brithYears, indexY));
		month.setViewAdapter(new DateArrayAdapter(this, brithMonths, indexM));
		day.setViewAdapter(new DateArrayAdapter(this, brithDays, indexD));

		year.setCurrentItem(indexY);
		month.setCurrentItem(indexM);
		day.setCurrentItem(indexD);

		updateDays(year, month, day);

		brithyear = brithYears[indexY];
		brithmonth = brithMonths[indexM];
		brithday = brithDays[indexD];
		constellation = ConstellationUtil.calculateConstellation(brithyear
				+ "-" + brithmonth + "-" + brithday);
		thisYear = bry;

		year.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				updateDays(year, month, day);
				brithyear = brithYears[newValue];

				int now = Integer.parseInt(thisYear);
				int select = Integer.parseInt(brithyear);

				if ((select - now) > 0) {
					// 选的不是今年了喔
					return;
				}

				et_age.setText("" + (now - select));

			}
		});

		month.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				updateDays(year, month, day);
				brithmonth = brithMonths[newValue];

				constellation = ConstellationUtil
						.calculateConstellation(brithyear + "-" + brithmonth
								+ "-" + brithday);
				et_constellation.setText(constellation);
			}
		});

		day.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				updateDays(year, month, day);
				brithday = brithDays[newValue];

				constellation = ConstellationUtil
						.calculateConstellation(brithyear + "-" + brithmonth
								+ "-" + brithday);
				et_constellation.setText(constellation);

			}
		});

	}

	@Override
	public void finish() {
		String brith = "";
		if (!brithyear.equals("") && !brithmonth.equals("")
				&& !brithday.equals("")) {
			save_brithyear = brithyear;
			save_brithmonth = brithmonth;
			save_brithday = brithday;

			brith = save_brithyear + "-" + save_brithmonth + "-"
					+ save_brithday;
		}

		boolean isSetBirthday = false;
		boolean isSetConstellations = false;
		if (!brith.equals("")) {
			ALLocalEnv.getLocalEnv().getMyProfile().setBirthday(brith);
			isSetBirthday = true;
			ALLocalEnv.getLocalEnv().getMyProfile().setAge(ALAgeFormatter.getAge(brith));
		}
		if (!constellation.equals("")) {
			ALLocalEnv.getLocalEnv().getMyProfile().setConstellations(constellation);
			isSetConstellations = true;
		}

		if (isSetBirthday && isSetConstellations) {
			// 发送保存信息广播
			User u = new User();
			u.setBirthday(brith);
			u.setConstellations(constellation);
			ALUiXmppRequestCreator.postALUiXmppModifyUserProfileEvent(u);

		}

		super.finish();
	}


	/**
	 * Updates day wheel. Sets max days according to selected month and year
	 */
	void updateDays(WheelView year, WheelView month, WheelView day) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR,
				calendar.get(Calendar.YEAR) + year.getCurrentItem());
		calendar.set(Calendar.MONTH, month.getCurrentItem());

		int maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
		day.setViewAdapter(new DateNumericAdapter(this, 1, maxDays, calendar
				.get(Calendar.DAY_OF_MONTH) - 1));
		int curDay = Math.min(maxDays, day.getCurrentItem() + 1);
		day.setCurrentItem(curDay - 1, true);
	}

	/**
	 * Adapter for numeric wheels. Highlights the current value.
	 */
	private class DateNumericAdapter extends NumericWheelAdapter {
		// Index of current item
		int currentItem;
		// Index of item to be highlighted
		int currentValue;

		/**
		 * Constructor
		 */
		public DateNumericAdapter(Context context, int minValue, int maxValue,
				int current) {
			super(context, minValue, maxValue);
			this.currentValue = current;
			setTextSize(25);
		}

		@Override
		protected void configureTextView(TextView view) {
			super.configureTextView(view);
//			if (currentItem == currentValue) {
//				view.setTextColor(0xFF0000F0);
//			}
			if (currentItem == currentValue) {
//				 view.setTextColor(ALColorUtils.parseColor("#3d3d3d"));
			}else{
//				 view.setTextColor(0xFF0000F0);
//				 view.setTextColor(ALColorUtils.parseColor("#7d7d7d"));
				
			}
			view.setTypeface(Typeface.SANS_SERIF);
		}

		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			currentItem = index;
			return super.getItem(index, cachedView, parent);
		}
	}

	/**
	 * Adapter for string based wheel. Highlights the current value.
	 */
	private class DateArrayAdapter extends ArrayWheelAdapter<String> {
		// Index of current item
		int currentItem;
		// Index of item to be highlighted
		int currentValue;

		/**
		 * Constructor
		 */
		public DateArrayAdapter(Context context, String[] items, int current) {
			super(context, items);
			this.currentValue = current;
			setTextSize(25);
		}

		protected void configureTextView(TextView view) {
			super.configureTextView(view);
			if (currentItem == currentValue) {
//				 view.setTextColor(ALColorUtils.parseColor("#3d3d3d"));
			}else{
//				 view.setTextColor(0xFF0000F0);
//				 view.setTextColor(ALColorUtils.parseColor("#7d7d7d"));
				
			}
			view.setTypeface(Typeface.SANS_SERIF);
		}

		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			currentItem = index;
			return super.getItem(index, cachedView, parent);
		}
	}
	
	private int getStringArrayIndex(String str[], String value) {

		int index = 0;

		for (int i = 0; i < str.length; i++) {

			if (value.equals(str[i]) || value == str[i]) {

				index = i;
			}
		}
		return index;
	}
}
